package com.mlethe.library.recyclerview.decoration;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.mlethe.library.recyclerview.listener.ItemDecorationListener;

/**
 * 分割线(StaggeredGridLayoutManager 模式分割线会占据item的高度)
 *
 * @author Mlethe
 * @date 2018/1/11
 */
public class GridItemDecoration extends RecyclerView.ItemDecoration {
    private Context mContext;
    private Drawable mDivider;
    private Drawable mMarginDivider;
    /**
     * 垂直空隙大小
     */
    private int mVerticalSize;
    /**
     * 水平空隙大小
     */
    private int mHorizontalSize;
    /**
     * 顶部Margin大小
     */
    private int mTopMarginSize;
    /**
     * 底部Margin大小
     */
    private int mBottomMarginSize;
    /**
     * 左边Margin大小
     */
    private int mLeftMarginSize;
    /**
     * 右边Margin大小
     */
    private int mRightMarginSize;
    /**
     * 最后一行未占满的竖直分割线是否显示
     */
    private boolean isShowLast = false;

    private ItemDecorationListener mItemDecorationListener;

    public GridItemDecoration() {
    }

    public GridItemDecoration(Context context) {
        this.mContext = context.getApplicationContext();
    }

    public GridItemDecoration setContext(Context context) {
        mContext = context.getApplicationContext();
        return this;
    }

    /**
     * 设置drawable
     *
     * @param drawableId
     */
    public GridItemDecoration setDrawable(@DrawableRes int drawableId) {
        if (mContext == null) {
            return this;
        }
        return setDrawable(ContextCompat.getDrawable(mContext, drawableId));
    }

    /**
     * 设置drawable
     *
     * @param drawable
     */
    public GridItemDecoration setDrawable(Drawable drawable) {
        mDivider = drawable;
        return this;
    }

    /**
     * 设置颜色
     *
     * @param colorRes
     */
    public GridItemDecoration setColor(@ColorRes int colorRes) {
        if (mContext == null) {
            return this;
        }
        return setColorInt(ContextCompat.getColor(mContext, colorRes));
    }

    /**
     * 设置颜色
     *
     * @param color
     */
    public GridItemDecoration setColorInt(@ColorInt int color) {
        mDivider = new ColorDrawable(color);
        return this;
    }

    /**
     * 设置颜色
     *
     * @param colorString
     */
    public GridItemDecoration setColor(String colorString) {
        return setColorInt(Color.parseColor(colorString));
    }

    /**
     * 设置边框drawable
     *
     * @param drawableId
     */
    public GridItemDecoration setMarginDrawable(@DrawableRes int drawableId) {
        if (mContext == null) {
            return this;
        }
        return setMarginDrawable(ContextCompat.getDrawable(mContext, drawableId));
    }

    /**
     * 设置边框drawable
     *
     * @param drawable
     */
    public GridItemDecoration setMarginDrawable(Drawable drawable) {
        mMarginDivider = drawable;
        return this;
    }

    /**
     * 设置边框颜色
     *
     * @param colorRes
     */
    public GridItemDecoration setMarginColor(@ColorRes int colorRes) {
        if (mContext == null) {
            return this;
        }
        return setMarginColorInt(ContextCompat.getColor(mContext, colorRes));
    }

    /**
     * 设置边框颜色
     *
     * @param color
     */
    public GridItemDecoration setMarginColorInt(@ColorInt int color) {
        mMarginDivider = new ColorDrawable(color);
        return this;
    }

    /**
     * 设置边框颜色
     *
     * @param colorString
     */
    public GridItemDecoration setMarginColor(String colorString) {
        return setMarginColorInt(Color.parseColor(colorString));
    }

    /**
     * 设置空隙大小
     *
     * @param size dp
     * @return
     */
    public GridItemDecoration setSize(float size) {
        return setSize(dp2px(size));
    }

    /**
     * 设置空隙大小
     *
     * @param size px
     * @return
     */
    public GridItemDecoration setSize(int size) {
        this.mVerticalSize = size;
        this.mHorizontalSize = size;
        return this;
    }

    /**
     * 设置垂直空隙大小
     *
     * @param size dp
     * @return
     */
    public GridItemDecoration setVerticalSize(float size) {
        return setVerticalSize(dp2px(size));
    }

    /**
     * 设置垂直空隙大小
     *
     * @param size px
     * @return
     */
    public GridItemDecoration setVerticalSize(int size) {
        this.mVerticalSize = size;
        return this;
    }

    /**
     * 设置水平空隙大小
     *
     * @param size dp
     * @return
     */
    public GridItemDecoration setHorizontalSize(float size) {
        return setHorizontalSize(dp2px(size));
    }

    /**
     * 设置水平空隙大小
     *
     * @param size px
     * @return
     */
    public GridItemDecoration setHorizontalSize(int size) {
        this.mHorizontalSize = size;
        return this;
    }

    /**
     * 设置左右Margin大小
     *
     * @param left  dp
     * @param right dp
     * @return
     */
    public GridItemDecoration setHorizontalMarginSize(float left, float right) {
        return setHorizontalMarginSize(dp2px(left), dp2px(right));
    }

    /**
     * 设置左右Margin大小
     *
     * @param left  px
     * @param right px
     * @return
     */
    public GridItemDecoration setHorizontalMarginSize(int left, int right) {
        this.mLeftMarginSize = left;
        this.mRightMarginSize = right;
        return this;
    }

    /**
     * 设置上下Margin大小
     *
     * @param top    dp
     * @param bottom dp
     * @return
     */
    public GridItemDecoration setVerticalMarginSize(float top, float bottom) {
        return setVerticalMarginSize(dp2px(top), dp2px(bottom));
    }

    /**
     * 设置上下Margin大小
     *
     * @param top    px
     * @param bottom px
     * @return
     */
    public GridItemDecoration setVerticalMarginSize(int top, int bottom) {
        this.mTopMarginSize = top;
        this.mBottomMarginSize = bottom;
        return this;
    }

    /**
     * 设置Margin大小（dp）
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     * @return
     */
    public GridItemDecoration setMarginSize(float left, float top, float right, float bottom) {
        return setMarginSize(dp2px(left), dp2px(top), dp2px(right), dp2px(bottom));
    }

    /**
     * 设置Margin大小（px）
     *
     * @param left   左
     * @param top    上
     * @param right  右
     * @param bottom 下
     * @return
     */
    public GridItemDecoration setMarginSize(int left, int top, int right, int bottom) {
        this.mLeftMarginSize = left;
        this.mTopMarginSize = top;
        this.mRightMarginSize = right;
        this.mBottomMarginSize = bottom;
        return this;
    }

    /**
     * 设置Margin大小（dp）
     *
     * @param size
     * @return
     */
    public GridItemDecoration setMarginSize(float size) {
        return setMarginSize(dp2px(size));
    }

    /**
     * 设置Margin大小（px）
     *
     * @param size
     * @return
     */
    public GridItemDecoration setMarginSize(int size) {
        this.mLeftMarginSize = size;
        this.mTopMarginSize = size;
        this.mRightMarginSize = size;
        this.mBottomMarginSize = size;
        return this;
    }

    /**
     * 设置左右Margin大小
     *
     * @param size dp
     * @return
     */
    public GridItemDecoration setHorizontalMarginSize(float size) {
        return setHorizontalMarginSize(dp2px(size));
    }

    /**
     * 设置左右Margin大小
     *
     * @param size px
     * @return
     */
    public GridItemDecoration setHorizontalMarginSize(int size) {
        this.mLeftMarginSize = size;
        this.mRightMarginSize = size;
        return this;
    }

    /**
     * 设置上下Margin大小
     *
     * @param size dp
     * @return
     */
    public GridItemDecoration setVerticalMarginSize(float size) {
        return setVerticalMarginSize(dp2px(size));
    }

    /**
     * 设置上下Margin大小
     *
     * @param size px
     * @return
     */
    public GridItemDecoration setVerticalMarginSize(int size) {
        this.mTopMarginSize = size;
        this.mBottomMarginSize = size;
        return this;
    }

    /**
     * 最后一个item未占满的 竖直\水平 分割线是否显示
     *
     * @param show true 显示，false 不显示
     * @return
     */
    public GridItemDecoration setLastShow(boolean show) {
        isShowLast = show;
        return this;
    }

    /**
     * 设置自定义分割线
     *
     * @param itemDecorationListener
     * @return
     */
    public GridItemDecoration setItemDecorationListener(ItemDecorationListener itemDecorationListener) {
        this.mItemDecorationListener = itemDecorationListener;
        return this;
    }

    /**
     * dp转px
     *
     * @param dp
     * @return
     */
    private int dp2px(float dp) {
        if (mContext == null) {
            return 0;
        }
        return dp2px(mContext, dp);
    }

    /**
     * dp转px
     *
     * @param dp
     * @return
     */
    protected int dp2px(Context context, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
    }

    /**
     * 设置条目周边的偏移量
     *
     * @param outRect 接收输出的Rect
     * @param view childView
     * @param parent RecyclerView
     * @param state RecyclerView的当前状态
     */
    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        mContext = null;
        int spanCount = getSpanCount(parent);
        if (spanCount == -1) {
            return;
        }
        int position = parent.getChildAdapterPosition(view);
        if (position < 0) {
            return;
        }
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter == null) {
            return;
        }
        int itemCount = adapter.getItemCount();
        if (position >= itemCount) {
            return;
        }
        if (mItemDecorationListener != null) {
            int startPosition = mItemDecorationListener.getStart();
            int dataSize = mItemDecorationListener.getDrawCount();
            if (startPosition >= 0 && position >= startPosition && dataSize > 0) {
                position -= startPosition;
                itemCount = dataSize;
                if (position >= itemCount) {
                    return;
                }
            } else {
                return;
            }
        }
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        int orientation;
        boolean reverseLayout;
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;
            orientation = manager.getOrientation();
            reverseLayout = manager.getReverseLayout();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) layoutManager;
            orientation = manager.getOrientation();
            reverseLayout = manager.getReverseLayout();
        } else {
            return;
        }
        if (reverseLayout) {
            if (orientation == RecyclerView.HORIZONTAL) {
                int right = 0;
                int top;
                int left = mHorizontalSize;
                int bottom;
                // 等差数列
                int eachHeight = (spanCount - 1) * mVerticalSize / spanCount;
                int dl = Math.abs(mVerticalSize - eachHeight);
                int topSize = position % spanCount * dl;
                if (isHorizontalFirstRow(position, spanCount)) {
                    // 第一行
                    top = mTopMarginSize;
                } else {
                    top = topSize;
                }
                if (isHorizontalLastRow(position, spanCount)) {
                    // 最后一行
                    bottom = mBottomMarginSize;
                } else {
                    bottom = eachHeight - topSize;
                }
                if (isHorizontalFirstColumn(position, spanCount)) {
                    // 第一列
                    right = mRightMarginSize;
                }
                if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                    // 最后一列
                    left = mLeftMarginSize;
                }
                outRect.set(left, top, right, bottom);
                return;
            }
            int left;
            int bottom = 0;
            int right;
            int top = mVerticalSize;
            // 等差数列
            int eachWidth = (spanCount - 1) * mHorizontalSize / spanCount;
            int dl = Math.abs(mHorizontalSize - eachWidth);
            int leftSize = position % spanCount * dl;
            if (isFirstColumn(position, spanCount)) {
                // 第一列
                left = mLeftMarginSize;
            } else {
                left = leftSize;
            }
            if (isLastColumn(position, spanCount)) {
                // 最后一列
                right = mRightMarginSize;
            } else {
                right = eachWidth - leftSize;
            }
            if (isFirstRow(position, spanCount)) {
                // 第一行
                bottom = mBottomMarginSize;
            }
            if (isLastRow(position, itemCount, spanCount)) {
                // 最后一行
                top = mTopMarginSize;
            }
            outRect.set(left, top, right, bottom);
            return;
        }
        if (orientation == RecyclerView.HORIZONTAL) {
            int left = 0;
            int top;
            int right = mHorizontalSize;
            int bottom;
            // 等差数列
            int eachHeight = (spanCount - 1) * mVerticalSize / spanCount;
            int dl = Math.abs(mVerticalSize - eachHeight);
            int topSize = position % spanCount * dl;
            if (isHorizontalFirstRow(position, spanCount)) {
                // 第一行
                top = mTopMarginSize;
            } else {
                top = topSize;
            }
            if (isHorizontalLastRow(position, spanCount)) {
                // 最后一行
                bottom = mBottomMarginSize;
            } else {
                bottom = eachHeight - topSize;
            }
            if (isHorizontalFirstColumn(position, spanCount)) {
                // 第一列
                left = mLeftMarginSize;
            }
            if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                // 最后一列
                right = mRightMarginSize;
            }
            outRect.set(left, top, right, bottom);
            return;
        }
        int left;
        int top = 0;
        int right;
        int bottom = mVerticalSize;
        // 等差数列
        int eachWidth = (spanCount - 1) * mHorizontalSize / spanCount;
        int dl = Math.abs(mHorizontalSize - eachWidth);
        int leftSize = position % spanCount * dl;
        if (isFirstColumn(position, spanCount)) {
            // 第一列
            left = mLeftMarginSize;
        } else {
            left = leftSize;
        }
        if (isLastColumn(position, spanCount)) {
            // 最后一列
            right = mRightMarginSize;
        } else {
            right = eachWidth - leftSize;
        }
        if (isFirstRow(position, spanCount)) {
            // 第一行
            top = mTopMarginSize;
        }
        if (isLastRow(position, itemCount, spanCount)) {
            // 最后一行
            bottom = mBottomMarginSize;
        }
        outRect.set(left, top, right, bottom);
    }

    /**
     * 绘制在图层的最下层
     *
     * @param canvas 画布
     * @param parent RecyclerView
     * @param state RecyclerView的当前状态
     */
    @Override
    public void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        // 列数
        int spanCount = getSpanCount(parent);
        if (spanCount == -1) {
            return;
        }

        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        int orientation;
        boolean reverseLayout;
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;
            orientation = manager.getOrientation();
            reverseLayout = manager.getReverseLayout();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) layoutManager;
            orientation = manager.getOrientation();
            reverseLayout = manager.getReverseLayout();
        } else {
            return;
        }
        if (reverseLayout) {
            if (orientation == RecyclerView.HORIZONTAL) {
                reverseDrawHorizontal(canvas, parent, spanCount);
            } else {
                reverseDraw(canvas, parent, spanCount);
            }
            return;
        }
        if (orientation == RecyclerView.HORIZONTAL) {
            drawHorizontal(canvas, parent, spanCount);
        } else {
            draw(canvas, parent, spanCount);
        }
    }

    /**
     * 绘制在图层的最上层
     *
     * @param canvas 画布
     * @param parent RecyclerView
     * @param state RecyclerView的当前状态
     */
    @Override
    public void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
    }

    /**
     * 正向绘制（水平方向滑动）
     *
     * @param canvas 画布
     * @param parent RecyclerView
     * @param spanCount 网络布置的格数
     */
    private void drawHorizontal(@NonNull Canvas canvas, @NonNull RecyclerView parent, int spanCount) {
        // 绘制
        int childCount = parent.getChildCount();
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter == null) {
            return;
        }
        int itemCount = adapter.getItemCount();
        int startPosition = -1;
        if (mItemDecorationListener != null) {
            startPosition = mItemDecorationListener.getStart();
            int dataSize = mItemDecorationListener.getDrawCount();
            if (startPosition >= 0 && dataSize > 0) {
                itemCount = dataSize;
            } else {
                return;
            }
        }
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(childView);

            if (mItemDecorationListener != null && startPosition >= 0) {
                if (position < startPosition) {
                    continue;
                }
                position -= startPosition;
            }

            if (position < 0 || position >= itemCount) {
                continue;
            }
            // 计算水平分割线的位置
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) childView.getLayoutParams();
            // 画水平分隔线
            // 第一行
            if (mMarginDivider != null && isHorizontalFirstRow(position, spanCount) && mTopMarginSize > 0) {
                int left = childView.getLeft() - layoutParams.leftMargin;
                if (isHorizontalFirstColumn(position, spanCount)) {
                    left -= mLeftMarginSize;
                }
                int right = childView.getRight() + layoutParams.rightMargin;
                if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                    right += mRightMarginSize;
                } else {
                    right += mHorizontalSize;
                }
                int bottom = childView.getTop() - layoutParams.topMargin;
                int top = bottom - mTopMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isHorizontalLastRow(position, spanCount)) {
                // 最后一行
                if (mMarginDivider != null && mBottomMarginSize > 0) {
                    int left = childView.getLeft() - layoutParams.leftMargin;
                    if (isHorizontalFirstColumn(position, spanCount)) {
                        left -= mLeftMarginSize;
                    }
                    int right = childView.getRight() + layoutParams.rightMargin;
                    if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                        right += mRightMarginSize;
                    } else {
                        right += mHorizontalSize;
                    }
                    int top = childView.getBottom() + layoutParams.bottomMargin;
                    int bottom = top + mBottomMarginSize;
                    mMarginDivider.setBounds(left, top, right, bottom);
                    mMarginDivider.draw(canvas);
                }
            } else {
                if (mDivider != null) {
                    if (position == itemCount - 1 && isHorizontalLastColumn(position, itemCount, spanCount)) {
                        if (isShowLast) {
                            int left = childView.getLeft() - layoutParams.leftMargin;
                            int right = childView.getRight() + layoutParams.rightMargin;
                            int top = childView.getBottom() + layoutParams.bottomMargin;
                            int bottom = top + mVerticalSize;
                            mDivider.setBounds(left, top, right, bottom);
                            mDivider.draw(canvas);
                        }
                    } else {
                        int left = childView.getLeft() - layoutParams.leftMargin;
                        int right = childView.getRight() + layoutParams.rightMargin;
                        right += mHorizontalSize;
                        int top = childView.getBottom() + layoutParams.bottomMargin;
                        int bottom = top + mVerticalSize;
                        mDivider.setBounds(left, top, right, bottom);
                        mDivider.draw(canvas);
                    }
                }
            }
            // 画垂直分割线
            // 第一列
            if (mMarginDivider != null && isHorizontalFirstColumn(position, spanCount) && mLeftMarginSize > 0) {
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                if (!isHorizontalLastRow(position, spanCount)) {
                    bottom += mVerticalSize;
                }
                int right = childView.getLeft() - layoutParams.leftMargin;
                int left = right - mLeftMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                // 最后一列
                if (mMarginDivider == null || mRightMarginSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                if (!isHorizontalLastRow(position, spanCount)) {
                    if (position == itemCount - 1) {
                        if (isShowLast) {
                            bottom += mVerticalSize;
                        }
                    } else {
                        bottom += mVerticalSize;
                    }
                }
                int left = childView.getRight() + layoutParams.rightMargin;
                int right = left + mRightMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            } else {
                if (mDivider == null || mHorizontalSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                int left = childView.getRight() + layoutParams.rightMargin;
                int right = left + mHorizontalSize;
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
        }
    }

    /**
     * 正向绘制（垂直方向滑动）
     *
     * @param canvas 画布
     * @param parent RecyclerView
     * @param spanCount 网络布置的格数
     */
    private void draw(@NonNull Canvas canvas, @NonNull RecyclerView parent, int spanCount) {
        // 绘制
        int childCount = parent.getChildCount();
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter == null) {
            return;
        }
        int itemCount = adapter.getItemCount();
        int startPosition = -1;
        if (mItemDecorationListener != null) {
            startPosition = mItemDecorationListener.getStart();
            int dataSize = mItemDecorationListener.getDrawCount();
            if (startPosition >= 0 && dataSize > 0) {
                itemCount = dataSize;
            } else {
                return;
            }
        }
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(childView);

            if (mItemDecorationListener != null && startPosition >= 0) {
                if (position < startPosition) {
                    continue;
                }
                position -= startPosition;
            }

            if (position < 0 || position >= itemCount) {
                continue;
            }
            // 计算水平分割线的位置
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) childView.getLayoutParams();
            // 画水平分隔线
            // 第一行
            if (mMarginDivider != null && isFirstRow(position, spanCount) && mTopMarginSize > 0) {
                int left = childView.getLeft() - layoutParams.leftMargin;
                if (isFirstColumn(position, spanCount)) {
                    left -= mLeftMarginSize;
                }
                int right = childView.getRight() + layoutParams.rightMargin;
                if (isLastColumn(position, spanCount)) {
                    right += mRightMarginSize;
                } else {
                    right += mHorizontalSize;
                }
                int bottom = childView.getTop() - layoutParams.topMargin;
                int top = bottom - mTopMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isLastRow(position, itemCount, spanCount)) {
                // 最后一行
                if (mMarginDivider != null && mBottomMarginSize > 0) {
                    int left = childView.getLeft() - layoutParams.leftMargin;
                    if (isFirstColumn(position, spanCount)) {
                        left -= mLeftMarginSize;
                    }
                    int right = childView.getRight() + layoutParams.rightMargin;
                    if (isLastColumn(position, spanCount)) {
                        right += mRightMarginSize;
                    } else if (position != itemCount - 1 || isShowLast) {
                        right += mHorizontalSize;
                    }
                    int top = childView.getBottom() + layoutParams.bottomMargin;
                    int bottom = top + mBottomMarginSize;
                    mMarginDivider.setBounds(left, top, right, bottom);
                    mMarginDivider.draw(canvas);
                }
            } else {
                if (mDivider != null) {
                    int left = childView.getLeft() - layoutParams.leftMargin;
                    int right = childView.getRight() + layoutParams.rightMargin;
                    if (!isLastColumn(position, spanCount)) {
                        right += mHorizontalSize;
                    }
                    int top = childView.getBottom() + layoutParams.bottomMargin;
                    int bottom = top + mVerticalSize;
                    mDivider.setBounds(left, top, right, bottom);
                    mDivider.draw(canvas);
                }
            }
            // 画垂直分割线
            // 第一列
            if (mMarginDivider != null && isFirstColumn(position, spanCount) && mLeftMarginSize > 0) {
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                if (!isLastRow(position, itemCount, spanCount)) {
                    bottom += mVerticalSize;
                }
                int right = childView.getLeft() - layoutParams.leftMargin;
                int left = right - mLeftMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isLastColumn(position, spanCount)) {
                // 最后一列
                if (mMarginDivider == null || mRightMarginSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                if (!isLastRow(position, itemCount, spanCount)) {
                    bottom += mVerticalSize;
                }
                int left = childView.getRight() + layoutParams.rightMargin;
                int right = left + mRightMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            } else {
                if (mDivider == null || (!isShowLast && position == itemCount - 1) || mHorizontalSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                int left = childView.getRight() + layoutParams.rightMargin;
                int right = left + mHorizontalSize;
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
        }
    }

    /**
     * 反向绘制（水平方向滑动）
     *
     * @param canvas 画布
     * @param parent RecyclerView
     * @param spanCount 网络布置的格数
     */
    private void reverseDrawHorizontal(@NonNull Canvas canvas, @NonNull RecyclerView parent, int spanCount) {
        // 绘制
        int childCount = parent.getChildCount();
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter == null) {
            return;
        }
        int itemCount = adapter.getItemCount();
        int startPosition = -1;
        if (mItemDecorationListener != null) {
            startPosition = mItemDecorationListener.getStart();
            int dataSize = mItemDecorationListener.getDrawCount();
            if (startPosition >= 0 && dataSize > 0) {
                itemCount = dataSize;
            } else {
                return;
            }
        }
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(childView);

            if (mItemDecorationListener != null && startPosition >= 0) {
                if (position < startPosition) {
                    continue;
                }
                position -= startPosition;
            }

            if (position < 0 || position >= itemCount) {
                continue;
            }
            // 计算水平分割线的位置
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) childView.getLayoutParams();
            // 画水平分隔线
            // 第一行
            if (mMarginDivider != null && isHorizontalFirstRow(position, spanCount) && mTopMarginSize > 0) {
                int left = childView.getLeft() - layoutParams.leftMargin;
                if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                    left -= mLeftMarginSize;
                } else {
                    left -= mHorizontalSize;
                }
                int right = childView.getRight() + layoutParams.rightMargin;
                if (isHorizontalFirstColumn(position, spanCount)) {
                    right += mRightMarginSize;
                }
                int bottom = childView.getTop() - layoutParams.topMargin;
                int top = bottom - mTopMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isHorizontalLastRow(position, spanCount)) {
                // 最后一行
                if (mMarginDivider != null && mBottomMarginSize > 0) {
                    int left = childView.getLeft() - layoutParams.leftMargin;
                    if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                        left -= mLeftMarginSize;
                    } else {
                        left -= mHorizontalSize;
                    }
                    int right = childView.getRight() + layoutParams.rightMargin;
                    if (isHorizontalFirstColumn(position, spanCount)) {
                        right += mRightMarginSize;
                    }
                    int top = childView.getBottom() + layoutParams.bottomMargin;
                    int bottom = top + mBottomMarginSize;
                    mMarginDivider.setBounds(left, top, right, bottom);
                    mMarginDivider.draw(canvas);
                }
            } else {
                if (mDivider != null) {
                    if (position == itemCount - 1 && isHorizontalLastColumn(position, itemCount, spanCount)) {
                        if (isShowLast) {
                            int left = childView.getLeft() - layoutParams.leftMargin;
                            int right = childView.getRight() + layoutParams.rightMargin;
                            int top = childView.getBottom() + layoutParams.bottomMargin;
                            int bottom = top + mVerticalSize;
                            mDivider.setBounds(left, top, right, bottom);
                            mDivider.draw(canvas);
                        }
                    } else {
                        int left = childView.getLeft() - layoutParams.leftMargin;
                        left -= mHorizontalSize;
                        int right = childView.getRight() + layoutParams.rightMargin;
                        int top = childView.getBottom() + layoutParams.bottomMargin;
                        int bottom = top + mVerticalSize;
                        mDivider.setBounds(left, top, right, bottom);
                        mDivider.draw(canvas);
                    }
                }
            }
            // 画垂直分割线
            // 第一列
            if (mMarginDivider != null && isHorizontalFirstColumn(position, spanCount) && mLeftMarginSize > 0) {
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                if (!isHorizontalLastRow(position, spanCount)) {
                    bottom += mVerticalSize;
                }
                int left = childView.getRight() + layoutParams.rightMargin;
                int right = left + mRightMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isHorizontalLastColumn(position, itemCount, spanCount)) {
                // 最后一列
                if (mMarginDivider == null || mRightMarginSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                if (!isHorizontalLastRow(position, spanCount)) {
                    if (position == itemCount - 1) {
                        if (isShowLast) {
                            bottom += mVerticalSize;
                        }
                    } else {
                        bottom += mVerticalSize;
                    }
                }
                int right = childView.getLeft() - layoutParams.leftMargin;
                int left = right - mLeftMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            } else {
                if (mDivider == null || mHorizontalSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                int right = childView.getLeft() - layoutParams.leftMargin;
                int left = right - mHorizontalSize;
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
        }
    }

    /**
     * 反向绘制（垂直方向滑动）
     *
     * @param canvas 画布
     * @param parent RecyclerView
     * @param spanCount 网络布置的格数
     */
    private void reverseDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent, int spanCount) {
        // 绘制
        int childCount = parent.getChildCount();
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter == null) {
            return;
        }
        int itemCount = adapter.getItemCount();
        int startPosition = -1;
        if (mItemDecorationListener != null) {
            startPosition = mItemDecorationListener.getStart();
            int dataSize = mItemDecorationListener.getDrawCount();
            if (startPosition >= 0 && dataSize > 0) {
                itemCount = dataSize;
            } else {
                return;
            }
        }
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(childView);

            if (mItemDecorationListener != null && startPosition >= 0) {
                if (position < startPosition) {
                    continue;
                }
                position -= startPosition;
            }

            if (position < 0 || position >= itemCount) {
                continue;
            }
            // 计算水平分割线的位置
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) childView.getLayoutParams();
            // 画水平分隔线
            // 第一行
            if (mMarginDivider != null && isFirstRow(position, spanCount) && mTopMarginSize > 0) {
                int left = childView.getLeft() - layoutParams.leftMargin;
                if (isFirstColumn(position, spanCount)) {
                    left -= mLeftMarginSize;
                }
                int right = childView.getRight() + layoutParams.rightMargin;
                if (isLastColumn(position, spanCount)) {
                    right += mRightMarginSize;
                } else {
                    right += mHorizontalSize;
                }
                int top = childView.getBottom() + layoutParams.bottomMargin;
                int bottom = top + mBottomMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isLastRow(position, itemCount, spanCount)) {
                // 最后一行
                if (mMarginDivider != null && mBottomMarginSize > 0) {
                    int left = childView.getLeft() - layoutParams.leftMargin;
                    if (isFirstColumn(position, spanCount)) {
                        left -= mLeftMarginSize;
                    }
                    int right = childView.getRight() + layoutParams.rightMargin;
                    if (isLastColumn(position, spanCount)) {
                        right += mRightMarginSize;
                    } else if (position != itemCount - 1 || isShowLast) {
                        right += mHorizontalSize;
                    }
                    int bottom = childView.getTop() - layoutParams.topMargin;
                    int top = bottom - mTopMarginSize;
                    mMarginDivider.setBounds(left, top, right, bottom);
                    mMarginDivider.draw(canvas);
                }
            } else {
                if (mDivider != null) {
                    int left = childView.getLeft() - layoutParams.leftMargin;
                    int right = childView.getRight() + layoutParams.rightMargin;
                    if (!isLastColumn(position, spanCount)) {
                        right += mHorizontalSize;
                    }
                    int bottom = childView.getTop() - layoutParams.topMargin;
                    int top = bottom - mVerticalSize;
                    mDivider.setBounds(left, top, right, bottom);
                    mDivider.draw(canvas);
                }
            }
            // 画垂直分割线
            // 第一列
            if (mMarginDivider != null && isFirstColumn(position, spanCount) && mLeftMarginSize > 0) {
                int top = childView.getTop() - layoutParams.topMargin;
                if (!isLastRow(position, itemCount, spanCount)) {
                    top -= mVerticalSize;
                }
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                int right = childView.getLeft() - layoutParams.leftMargin;
                int left = right - mLeftMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            }
            if (isLastColumn(position, spanCount)) {
                // 最后一列
                if (mMarginDivider == null || mRightMarginSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                if (!isLastRow(position, itemCount, spanCount)) {
                    top -= mVerticalSize;
                }
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                int left = childView.getRight() + layoutParams.rightMargin;
                int right = left + mRightMarginSize;
                mMarginDivider.setBounds(left, top, right, bottom);
                mMarginDivider.draw(canvas);
            } else {
                if (mDivider == null || (!isShowLast && position == itemCount - 1) || mHorizontalSize <= 0) {
                    continue;
                }
                int top = childView.getTop() - layoutParams.topMargin;
                int bottom = childView.getBottom() + layoutParams.bottomMargin;
                int left = childView.getRight() + layoutParams.rightMargin;
                int right = left + mHorizontalSize;
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
        }
    }

    /**
     * 第一列
     *
     * @return
     */
    private boolean isFirstColumn(int position, int spanCount) {
        // 当前位置%列数 == 0
        return position % spanCount == 0;
    }

    /**
     * 最后一列
     *
     * @return
     */
    private boolean isLastColumn(int position, int spanCount) {
        // 当前位置%列数 == 列数 - 1
        return position % spanCount == spanCount - 1;
    }

    /**
     * 第一行
     *
     * @return
     */
    private boolean isFirstRow(int position, int spanCount) {
        // 当前的位置 < 列数
        return position < spanCount;
    }

    /**
     * 最后一行
     *
     * @return
     */
    private boolean isLastRow(int position, int itemCount, double spanCount) {
        // (当前的位置 + 1) / 列数 == 总数 / 列数
        return Math.ceil((position + 1) / spanCount) == Math.ceil(itemCount / spanCount);
    }

    /**
     * 第一行 RecyclerView.HORIZONTAL
     *
     * @return
     */
    private boolean isHorizontalFirstRow(int position, int spanCount) {
        // 当前位置%列数 == 0
        return position % spanCount == 0;
    }

    /**
     * 最后一行 RecyclerView.HORIZONTAL
     *
     * @return
     */
    private boolean isHorizontalLastRow(int position, int spanCount) {
        // 当前位置%列数 == 列数 - 1
        return position % spanCount == spanCount - 1;
    }

    /**
     * 第一列 RecyclerView.HORIZONTAL
     *
     * @return
     */
    private boolean isHorizontalFirstColumn(int position, int spanCount) {
        // 当前的位置 < 列数
        return position < spanCount;
    }

    /**
     * 最后一列 RecyclerView.HORIZONTAL
     *
     * @return
     */
    private boolean isHorizontalLastColumn(int position, int itemCount, double spanCount) {
        // (当前的位置 + 1) / 列数 == 总数 / 列数
        return Math.ceil((position + 1) / spanCount) == Math.ceil(itemCount / spanCount);
    }

    /**
     * 获取网络布置的格数
     *
     * @param parent RecyclerView
     * @return 网络布置的格数
     */
    private int getSpanCount(RecyclerView parent) {
        // 获取列数  GridLayout
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            return gridLayoutManager.getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager staggeredGridLayoutManager = ((StaggeredGridLayoutManager) layoutManager);
            return staggeredGridLayoutManager.getSpanCount();
        }
        return -1;
    }
}
